﻿using Microsoft.AspNetCore.Mvc;
using star_questionnair.Models;
using star_questionnair.Services;

namespace star_questionnair.Controllers;

[ApiController]
[Route("api/[controller]")]
public class QuestionController : ControllerBase
    {
        private readonly IQuestionService _questionService;

        public QuestionController(IQuestionService questionService)
        {
            _questionService = questionService;
        }

        /// <summary>
        /// 创建问题
        /// </summary>
        [HttpPost("create")]
        public async Task<IActionResult> CreateQuestion([FromBody] Question question)
        {
            if (question == null)
                return BadRequest("Invalid question data.");

            await _questionService.InsertQuestionAsync(question.QuestionnaireId, question.Type, question.Content);
            var createdQuestion = await _questionService.GetQuestionAfterCreateAsync(question);
            return CreatedAtAction(nameof(GetQuestionById), new { id = createdQuestion.Id }, createdQuestion);
        }

        /// <summary>
        /// 根据id查询问题
        /// </summary>
        [HttpGet("get/{id}")]
        public async Task<IActionResult> GetQuestionById(int id)
        {
            var question = await _questionService.GetQuestionByIdAsync(id);
            if (question == null)
                return NotFound("Question not found.");
            return Ok(question);
        }

        /// <summary>
        /// 更新问题
        /// </summary>
        [HttpPut("update")]
        public async Task<IActionResult> UpdateQuestion([FromBody] Question question)
        {
            if (question == null)
                return BadRequest("Invalid question data.");

            try
            {
                await _questionService.UpdateQuestionAsync(question);
                return Ok("Question updated successfully.");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Update failed: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据id删除问题
        /// </summary>
        [HttpDelete("delete/{id}")]
        public async Task<IActionResult> DeleteQuestion(int id)
        {
            await _questionService.DeleteQuestionAsync(id);
            return Ok("Question deleted successfully.");
        }

        /// <summary>
        /// 显示一个问题的所有选项
        /// </summary>
        [HttpPost("display-options")]
        public async Task<IActionResult> DisplayOptions([FromBody] Question question)
        {
            var options = await _questionService.DisplayOptionsAsync(question);
            return Ok(options);
        }
    }